package com.wz.project.api.agv.controller;

import com.wz.project.agv.quene.domain.AgvQuene;
import com.wz.project.agv.quene.mapper.AgvQueneMapper;
import com.wz.project.agv.quene.service.impl.AgvQueneServiceImpl;
import com.wz.project.api.agv.domain.*;
import com.wz.project.log.log.domain.WmsAgvLog;
import com.wz.project.log.log.service.impl.WmsAgvLogServiceImpl;
import com.wz.project.mydo.domain.MydoJob;
import com.wz.project.mydo.domain.MydoJobs;
import com.wz.project.mydo.mydojob.mapper.MydoJobMapper;
import com.wz.project.mydo.mydojob.mapper.MydoJobsMapper;
import com.wz.project.mydo.mydojob.service.IMydoJobService;
import com.wz.project.position.code.domain.PositionCode;
import com.wz.project.position.code.service.impl.PositionCodeServiceImpl;
import com.wz.project.system.ssj.domain.DeviceAgvSsj;
import com.wz.project.system.ssj.service.impl.DeviceAgvSsjServiceImpl;
import com.wz.project.util.DateUtill;
import com.wz.project.util.JsonUtil;
import com.wz.project.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureQuery;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import static com.wz.common.utils.Threads.sleep;

@RestController
@RequestMapping("/agvs")
//@EnableScheduling
public class AgvController {
    static final String sendurl = "http://10.9.3.231:8181/rcms/services/rest/hikRpcService/genAgvSchedulingTask";
    static final String contuieurl = "http://10.9.3.231:8181/rcms/services/rest/hikRpcService/continueTask";
    @Autowired
    MydoJobsMapper mydoJobRepository;
    @Autowired
    AgvQueneServiceImpl agvQueneService;
    @Autowired
    WmsAgvLogServiceImpl agvLogService;
    @Autowired
    AgvQueneMapper agvQueneMapper;
    @Autowired
    PositionCodeServiceImpl positionCodeService;
    @Autowired
    DeviceAgvSsjServiceImpl ssjService;

    @Autowired
    private IMydoJobService jobService;
    @Autowired
    private EntityManager entityManager;

    /**
     * 下发agv
     *
     * @param
     * @return
     */
    @RequestMapping("/send/task")
    @Transactional
//    @Scheduled(fixedRate = 3000)
    public void sendTask() {
        WmsAgvLog wmsAgvLog = new WmsAgvLog();
        AgvRequest agvRequest1 = new AgvRequest();
        AgvResponseResult rest = null;
        MydoJob mydoJob1 = new MydoJob();
        List<AgvQuene> agvQuenes = agvQueneMapper.selectTopOnes("0");
        if (agvQuenes != null && agvQuenes.size() > 0) {
            try {
                for (AgvQuene agvQuene : agvQuenes) {
                    wmsAgvLog.setAddress(sendurl);
                    wmsAgvLog.setBackCode("海康AGV");
                    wmsAgvLog.setSendCode("福来瑞达WMS");
                    wmsAgvLog.setTypes("下发作业");
                    agvRequest1.setTaskCode(agvQuene.getTask_code());
                    agvRequest1.setReqCode(agvQuene.getTask_code());
                    agvRequest1.setTaskTyp(agvQuene.getType());

                    agvRequest1.setReqTime(DateUtill.localDateTime(DateUtill.DATE_TIME_PATTERN));
                    List<AgvRequest.PositionCodePathBean> positionCodePathBeans = new LinkedList<>();
                    positionCodePathBeans.add(new AgvRequest.PositionCodePathBean(agvQuene.getPosition_one(), "00"));
                    positionCodePathBeans.add(new AgvRequest.PositionCodePathBean(agvQuene.getPosition_two(), "00"));

                    agvRequest1.setPositionCodePath(positionCodePathBeans);
                    String json = JsonUtil.getJson(agvRequest1);
                    System.err.println(json);
                    rest = RestTemplateUtil.rest(sendurl, RestTemplateUtil.APPLICATION_JSON, json, AgvResponseResult.class);
                    System.err.println(rest.toString());
                    if (rest.getCode().equals("0")) {
                        // 下发改2
                        wmsAgvLog.setInJson(json);
                        wmsAgvLog.setBackJson(rest.toString());
                        wmsAgvLog.setStatus(String.valueOf(1));
                        agvLogService.insertWmsAgvLog(wmsAgvLog);
                        agvQuene.setStatus("1");
                        agvQuene.setReq_code(rest.getReqCode());
                        agvQuene.setXfsj(DateUtill.localDateTime(DateUtill.DATE_TIME_PATTERN));
                        agvQueneMapper.updateAgvQuene(agvQuene);

                    } else {
                        // 下发改2
                        wmsAgvLog.setInJson(json);
                        wmsAgvLog.setBackJson(rest.toString());
                        wmsAgvLog.setStatus(String.valueOf(2));
                        agvLogService.insertWmsAgvLog(wmsAgvLog);
                    }
                }
            } catch (Exception e) {
                wmsAgvLog.setInJson("");
                wmsAgvLog.setStatus(String.valueOf(2));
                agvLogService.insertWmsAgvLog(wmsAgvLog);
            }
        }
    }


    /**
     * 继续执行任务 AGV
     *
     * @param
     * @return
     */
    @RequestMapping("/continue/task")
    @Transactional
//    @Scheduled(fixedRate = 2000)
    public void continueTask() {

        AgvContinueTask agvRequest1 = new AgvContinueTask();
        AgvResponseResult rest = null;
        List<AgvQuene> agvQuene = agvQueneService.selectQqs(String.valueOf(1));
        if (agvQuene != null) {
            for (AgvQuene agvQuene1 : agvQuene) {
                WmsAgvLog wmsAgvLog = new WmsAgvLog();
                wmsAgvLog.setAddress(contuieurl);
                wmsAgvLog.setBackCode("海康AGV");
                wmsAgvLog.setSendCode("福来瑞达WMS");
                wmsAgvLog.setTypes("继续执行任务");
                PositionCode positionCode1 = new PositionCode();
//                String positionFour = agvQuene1.getPosition_four();
//                String lx = agvQuene1.getLx();
//                positionCode1.setName(positionFour);
//                positionCode1.setLx(Integer.parseInt(lx));
//                PositionCode positionCode = positionCodeService.selectByNameAndLx(positionCode1);
//                // 如果是车间的接驳架

                agvRequest1.setTaskCode(String.valueOf(agvQuene1.getTask_code()));
                agvRequest1.setReqCode(String.valueOf(agvQuene1.getReq_code()));
                agvRequest1.setReqTime(DateUtill.localDateTime(DateUtill.DATE_TIME_PATTERN));
                String json = JsonUtil.getJson(agvRequest1);
                rest = RestTemplateUtil.rest(contuieurl, RestTemplateUtil.APPLICATION_JSON, json, AgvResponseResult.class);
                if (rest.getCode().equals("0")) {
                    // 取完改3
                    wmsAgvLog.setInJson(json);
                    wmsAgvLog.setBackJson(rest.toString());
                    wmsAgvLog.setStatus(String.valueOf(1));
                    agvLogService.insertWmsAgvLog(wmsAgvLog);
                    agvQuene1.setQq("2");
                    agvQueneService.updateAgvQuene(agvQuene1);

                } else {
                    wmsAgvLog.setInJson(json);
                    wmsAgvLog.setBackJson(rest.toString());
                    wmsAgvLog.setStatus(String.valueOf(2));
                    agvLogService.insertWmsAgvLog(wmsAgvLog);
                }
            }
//                }
            // 如果是立库的设备 只有拆盘机和立库的agv对接线体
//                if (lx.equals("2")) {
//                    if (positionCode != null && positionCode.getKx() == 1 && positionCode.getStatus().equals("3")) {
//                        agvRequest1.setTaskCode(String.valueOf(agvQuene1.getTask_code()));
//                        agvRequest1.setReqCode(String.valueOf(agvQuene1.getReq_code()));
//                        agvRequest1.setReqTime(DateUtill.localDateTime(DateUtill.DATE_TIME_PATTERN));
//                        String json = JsonUtil.getJson(agvRequest1);
//                        rest = RestTemplateUtil.rest(contuieurl, RestTemplateUtil.APPLICATION_JSON, json, AgvResponseResult.class);
//                        if (rest.getCode().equals("0")) {
//                            // 取完改3
//                            wmsAgvLog.setInJson(json);
//                            wmsAgvLog.setBackJson(rest.toString());
//                            wmsAgvLog.setStatus(String.valueOf(1));
//                            agvLogService.insertWmsAgvLog(wmsAgvLog);
//                            agvQuene1.setQq("2");
//                            agvQueneService.updateAgvQuene(agvQuene1);
//                        } else {
//                            wmsAgvLog.setInJson(json);
//                            wmsAgvLog.setBackJson(rest.toString());
//                            wmsAgvLog.setStatus(String.valueOf(2));
//                            agvLogService.insertWmsAgvLog(wmsAgvLog);
//                        }
//                    }
//                }
        }
//        }
    }

    /**
     * 海康调wms接口，设备返回通知
     *
     * @param request
     * @return
     */
    @RequestMapping("/agvCallbackService/agvCallback")
    @Transactional
    public AgvReturn agvResult(@RequestBody AgvSendRequest request) {
        System.err.println(request.toString());
        AgvReturn agvReturn = null;
        agvReturn = new AgvReturn();
        String taskCode = request.getTaskCode();
        WmsAgvLog wmsAgvLog = new WmsAgvLog();
        AgvQuene agvQuene = agvQueneMapper.selectAgvQueneByTaskCode(taskCode);
        try {
            wmsAgvLog.setAddress("http://127.0.0.1:8011/agv/agvCallbackService/agvCallback");
            wmsAgvLog.setBackCode("福来瑞达WMS");
            wmsAgvLog.setSendCode("海康AGV");
            wmsAgvLog.setTypes("反馈作业状态");
            if (request.getMethod().equals("cancel")) {
                System.err.println("当前AGV执行状态  cancel");
            }
            if (request.getMethod().equals("start")) {

                agvReturn.setReqcode(request.getReqCode());
                agvReturn.setCode("0");
                agvReturn.setMsg("成功");
                System.err.println("当前AGV执行状态  start");
            }

            //放货完成 放到接驳口或者放到 产线接驳口
            if (request.getMethod().equals("end")) {
                if (agvQuene != null) {
//                    String position_four = agvQuene.getPosition_four();
//                    // 更新站点
//                    PositionCode positionCode = positionCodeService.selectByName(position_four);
//                    if (positionCode != null) {
//                        int sb = positionCode.getSb();
//                        //1为车间接驳架 2设备线体
//                        int lx = positionCode.getLx();
//                        int inorout = positionCode.getInorout();
//                        if (lx == 1) {
//                            positionCode.setStatus("2");
//                            positionCodeService.updatePositionCode(positionCode);
//                        }
//                        if (lx == 2) {
//                            if (sb == 2) {
//                                positionCode.setStatus("2");
//                                positionCodeService.updatePositionCode(positionCode);
//                            }
//                            if (sb == 1) {
//                                positionCode.setStatus("0");
//                                positionCodeService.updatePositionCode(positionCode);
//                            }
//                        }
//                    }
//                }
//                MydoJobs mydoJob = mydoJobRepository.selectJobByTask(String.valueOf(agvQuene.getTask_no()));
//                if (mydoJob != null) {
//                    if (mydoJob.getIn_or_out().equals("1") || mydoJob.getIn_or_out().equals("2")) {
//                        mydoJob.setExecution_phase("3");
//                        mydoJob.setStatus("3");
//                        mydoJobRepository.updateJob(mydoJob);
//                    }
//                    if (mydoJob.getIn_or_out().equals("21")) {
//                        mydoJob.setFinish_time(DateUtill.localDateTime(DateUtill.DATE_TIME_PATTERN));
//                        mydoJobRepository.insertFinish(mydoJob.getJob_id());
//                        mydoJobRepository.deleteJobById(mydoJob.getJob_id());
//                    }
//                }
//
//                agvQuene.setJssj(DateUtill.localDateTime(DateUtill.DATE_TIME_PATTERN));
//                agvQueneService.updateAgvQuene(agvQuene);
//                agvQueneService.insertAgvQueneFinish(agvQuene);
//                agvQueneService.deleteAgvQueneById(agvQuene.getTask_no());

                      agvEnd(String.valueOf(agvQuene.getTask_no()));
                }
                agvReturn.setReqcode(request.getReqCode());
                agvReturn.setCode("0");
                agvReturn.setMsg("成功");
                System.err.println("当前AGV执行状态  end");
            }
            //取货完成  修改device_agv_ssj 表内的值 如果存在将其改为 1
            if (request.getMethod().equals("outbin")) {
                if (agvQuene != null) {
//                    String positionThree = agvQuene.getPosition_three();
//                    // 更新站点
//                    PositionCode positionCode = positionCodeService.selectByName(positionThree);
//
//                    if (positionCode != null) {
//                        //1 拆盘机  2立库线体
//                        int sb = positionCode.getSb();
//                        //1为车间接驳架 2设备线体
//                        int lx = positionCode.getLx();
//                        int inorout = positionCode.getInorout();
//                        if (lx == 1) {
//                            positionCode.setStatus("1");
//                            positionCodeService.updatePositionCode(positionCode);
//                        }
//                        if (lx == 2) {
//                            if (sb == 2) {
//                                positionCode.setStatus("1");
//                                positionCodeService.updatePositionCode(positionCode);
//                            }
//                            if (sb == 1) {
//                                positionCode.setStatus("0");
//                                positionCodeService.updatePositionCode(positionCode);
//                            }
//                        }
//                    }

                    agvOutbin(String.valueOf(agvQuene.getTask_no()));

                }
                agvReturn.setReqcode(request.getReqCode());
                agvReturn.setCode("0");
                agvReturn.setMsg("成功");
                System.err.println("当前AGV执行状态  outbin");
            }
            // 请求放货 如果是放货接驳架查询 position_code 的值 如果是入库则查询监控是否空闲 调用继续执行任务的接口
            if (request.getMethod().equals("qq")) {
                //TODO 查监控是否空闲，如果空闲直接放置   或者根据站点表查询目标站点
                if (agvQuene != null && agvQuene.getQq().equals("0")) {
                    // 根据类型查询是去车间还是设备的
                    agvQuene.setReq_code(request.getReqCode());
                    agvQuene.setQq("1");
                    agvQueneService.updateAgvQuene(agvQuene);
                    // 如果是车间的接驳架
                    agvReturn.setReqcode(request.getReqCode());
                    agvReturn.setCode("0");
                    agvReturn.setMsg("成功");
                    System.err.println("当前AGV执行状态  qq");
                }
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            agvReturn.setReqcode(request.getReqCode());
            agvReturn.setMsg("失败");
            agvReturn.setCode("0");
            wmsAgvLog.setStatus("1");
            wmsAgvLog.setInJson(request.toString());
            wmsAgvLog.setBackJson(agvReturn.toString());
            agvLogService.insertWmsAgvLog(wmsAgvLog);
            return agvReturn;
        }
        wmsAgvLog.setStatus("1");
        wmsAgvLog.setInJson(request.toString());
        wmsAgvLog.setBackJson(agvReturn.toString());
        agvLogService.insertWmsAgvLog(wmsAgvLog);
        return agvReturn;
    }

    /**
     * agv执行完成
     * @param taskNo
     */
    public void agvEnd(String taskNo) {
        StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("proc_agv_end");
        StoredProcedureQuery parameter = storedProcedureQuery
                .registerStoredProcedureParameter("v_task_no", String.class, ParameterMode.IN)
                .registerStoredProcedureParameter("v_result", Integer.class, ParameterMode.OUT)
                .registerStoredProcedureParameter("v_result_msg", String.class, ParameterMode.OUT);
        parameter.setParameter("v_task_no", taskNo);
        //执行
        storedProcedureQuery.execute();
        //获取返回结果
        Integer result = (Integer) storedProcedureQuery.getOutputParameterValue("v_result");
        String msg = (String) storedProcedureQuery.getOutputParameterValue("v_result_msg");
        System.err.println("执行存储过程{proc_agv_end} 返回信息：" + msg);

    }

    /**
     * AGV 取货完成
     * @param taskNo
     */
    public void agvOutbin(String taskNo) {
        StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("proc_agv_outbin");
        StoredProcedureQuery parameter = storedProcedureQuery
                .registerStoredProcedureParameter("v_task_no", String.class, ParameterMode.IN)
                .registerStoredProcedureParameter("v_result", Integer.class, ParameterMode.OUT)
                .registerStoredProcedureParameter("v_result_msg", String.class, ParameterMode.OUT);
        parameter.setParameter("v_task_no", taskNo);        //执行
        storedProcedureQuery.execute();
        //获取返回结果
        Integer result = (Integer) storedProcedureQuery.getOutputParameterValue("v_result");
        String msg = (String) storedProcedureQuery.getOutputParameterValue("v_result_msg");
        System.err.println("执行存储过程{proc_agv_outbin} 返回信息：" + msg);
    }


}

